package com.ziyunying.weather.api

import android.content.Context
import com.qweather.sdk.JWTGenerator
import com.qweather.sdk.QWeather
import com.qweather.sdk.basic.Lang
import com.qweather.sdk.basic.Unit
import com.qweather.sdk.parameter.weather.WeatherParameter
import com.qweather.sdk.response.error.ErrorResponse
import com.qweather.sdk.response.weather.WeatherNowResponse
import com.qweather.sdk.Callback
import com.qweather.sdk.response.weather.WeatherDailyResponse
import javax.inject.Inject
import javax.inject.Singleton

@Singleton
class QWeatherApi @Inject constructor(
    context: Context, host: String, privateKey: String, projectId: String, kid: String
) {
    private val qWeatherInstance: QWeather = QWeather.getInstance(context, host).apply {

    }

    init {
        val jwtGenerator = JWTGenerator(privateKey, projectId, kid)
        qWeatherInstance.setTokenGenerator(jwtGenerator)
    }

    // 实时天气
    fun fetchWeatherNow(
        location: String,
        onSuccess: (WeatherNowResponse?) -> kotlin.Unit,
        onFailure: (ErrorResponse?) -> kotlin.Unit,
        onException: (Throwable?) -> kotlin.Unit
    ) {
        val parameter = WeatherParameter(location).lang(Lang.ZH_HANS).unit(Unit.METRIC)

        qWeatherInstance.weatherNow(parameter, object : Callback<WeatherNowResponse?> {
            override fun onSuccess(response: WeatherNowResponse?) {
                onSuccess(response)
            }

            override fun onFailure(errorResponse: ErrorResponse?) {
                onFailure(errorResponse)
            }

            override fun onException(e: Throwable?) {
                onException(e)
            }
        })
    }

    // 七天的天气预报
    fun fetchWeather7d(
        location: String,
        onSuccess: (WeatherDailyResponse?) -> kotlin.Unit,
        onFailure: (ErrorResponse?) -> kotlin.Unit,
        onException: (Throwable?) -> kotlin.Unit
    ) {
        val parameter = WeatherParameter(location).lang(Lang.ZH_HANS).unit(Unit.METRIC)

        qWeatherInstance.weather7d(parameter, object : Callback<WeatherDailyResponse?> {
            override fun onSuccess(response: WeatherDailyResponse?) {
                onSuccess(response)
            }

            override fun onFailure(errorResponse: ErrorResponse?) {
                onFailure(errorResponse)
            }

            override fun onException(e: Throwable?) {
                onException(e)
            }

        })
    }
}
